package com.swak.vertx.remote;

import com.swak.utils.StringUtils;
import com.swak.vertx.protocol.im.ImContext;
import com.swak.vertx.protocol.im.ImContext.ImRequest;

import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;

/**
 * IP 信息
 * 
 * @author DELL
 */
public class IP {

	private String text;

	public String getText() {
		return text;
	}

	public IP setText(String text) {
		this.text = text;
		return this;
	}

	public static IP parse(RoutingContext context) {
		return new IP().setText(getRemoteAddr(context.request()));
	}

	public static String getRemoteAddr(HttpServerRequest request) {
		String remoteAddr = request.getHeader("X-Real-IP");
		if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("X-Forwarded-For");
		} else if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("Proxy-Client-IP");
		} else if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("WL-Proxy-Client-IP");
		}
		return remoteAddr != null ? remoteAddr
				: (request.remoteAddress() != null ? request.remoteAddress().host() : null);
	}

	public static IP parse(ImContext context) {
		return new IP().setText(getRemoteAddr(context.request()));
	}

	public static String getRemoteAddr(ImRequest request) {
		String remoteAddr = request.getHeader("X-Real-IP");
		if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("X-Forwarded-For");
		} else if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("Proxy-Client-IP");
		} else if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("WL-Proxy-Client-IP");
		}
		return remoteAddr != null ? remoteAddr : request.remoteAddress();
	}
}
